require 'logger'

# Example:
#
# Log.set_log_path ("xxxx.log")
# DEBUG = false
# if DEBUG
# Log.set_level Logger::DEBUG
# else
# Log.set_level Logger::INFO
# end
# Log.set_stdout_flag false
#
# Log.debug("fsdfdfdff")
# Log.info
# Log.warn
# Log.error
# Log.fatal

module Log
  @@logger_stdout = nil
  @@logger_logfile = nil
  @@logfile = nil
  @@stdout_flag = true

  def self.init
    if @@logger_stdout.nil? && @@stdout_flag
      @@logger_stdout = Logger.new(STDOUT)
      @@logger_stdout.datetime_format = '%Y-%m-%d %H:%M:%S'
      @@logger_stdout.formatter = proc {|severity, datetime, _progname, msg|
        "#{severity}, #{datetime}: #{msg}\n"
      }
    end

    if @@logger_logfile.nil?
      unless @@logfile.nil? # 保留7天，每个不超过100M
        @@logger_logfile = Logger.new(@@logfile, shift_age = 7, shift_size = 104_857_600)
        @@logger_logfile.datetime_format = '%Y-%m-%d %H:%M:%S'
        @@logger_logfile.formatter = proc {|severity, datetime, _progname, msg|
          "#{severity}, #{datetime}: #{msg}\n"
        }
      end
    end
  end

  def self.method_missing(method_symbol, *arg)
    init
    if arg[0].class == String
      str = arg[0].encode(Encoding.default_external) # 在Linux和Win7下自动转成OS的默认编码
    else
      str = arg[0]
    end
    @@logger_stdout.send(method_symbol, str) if @@logger_stdout && @@stdout_flag
    @@logger_logfile.send(method_symbol, str) if @@logger_logfile
  end

  def self.set_log_path(logpath)
    @@logfile = logpath if @@logfile.nil?
    init
  end

  def self.set_level(level)
    init
    @@logger_stdout.level = level if @@logger_stdout
    @@logger_logfile.level = level if @@logger_logfile
  end

  def self.set_logfile_level(level)
    @@logger_logfile.level = level if @@logger_logfile
  end

  def self.set_stdout_flag(flag)
    @@stdout_flag = flag
  end
end
